package com.translate.web.api.controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.common.util.GenerateRandomCode;
import com.email.EmailUtil;
import com.response.vo.ResponseModel;
import com.translate.web.api.util.FileReaderContent;
import com.translate.web.config.Template;
import com.translate.web.constant.RedisConstant;
import com.translate.web.param.EmailParam;

import cn.hutool.extra.mail.MailAccount;

/**
 * 发送邮箱验证码
 * @author 111
 *
 */
@RestController
@RequestMapping("/email")
public class SendEmailConctroller {

	private EmailUtil emailUtil;
	
	private RedisTemplate<String, String> redisTemplate;

	private ResourceLoader resourceLoader;
	
	Template template;
	
	@Autowired
    public void setTemplate(Template template) {
        this.template = template;
    }
	
	@Autowired
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
	
	public SendEmailConctroller(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}
	
	
	@PostMapping("/sendMail")
	public ResponseModel<Integer> sendMail(@RequestBody @Validated EmailParam emailParam) {
		
		String code = GenerateRandomCode.getSixNum();
		
		ValueOperations<String, String> valueOperations  = this.redisTemplate.opsForValue();
		
		String email =  emailParam.getEmail();
		
		String key = RedisConstant.getEmailKey(email);
		
		valueOperations.set(key, code, 5, TimeUnit.MINUTES);
		
		
		Resource resource = resourceLoader.getResource(template.getVerificationCodeTemplate());
		
		try {
			String content = FileReaderContent.read(resource.getInputStream());
			
			if (null == content) {
				return ResponseModel.<Integer>error(500, "验证码模板读取失败");
			}
			
			content = content.replace("${code}", code).trim();
			
			emailUtil.sendMessage(email, "科藤学术中心邮箱验证", content, true);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ResponseModel.<Integer>success(1);
		
	}

	
	@Autowired
	public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
}
